#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import os
import json

def parse_configs(psv_path):
	psv_code_fd = open(psv_path,"r",encoding='gb18030', errors='ignore')
	psv_code = psv_code_fd.read()

	for item in frv_config.keys():
		psv_code = psv_code.replace("`"+item,str(frv_config[item]))

	return psv_code

def vp_psv2sv(psv_path,sv_path):
	psv_code = psv_path # open(psv_path,"r")
	psv_code_gen = open(sv_path,"w",encoding='gb18030', errors='ignore')
	
	sys_stdout = sys.stdout
	sys.stdout = psv_code_gen
	
	code_lines = psv_code.split("\n")
	
	it = 0
	while it < len(code_lines):
		line = code_lines[it]
		if line == "`psv_begin":
			pycode = []
			it = it + 1
			line = code_lines[it]
			while line != "`psv_end":
				pycode.append(line+"\n")
				it = it + 1
				line = code_lines[it]
			pycode_src = "".join(pycode)
			exec(pycode_src)
		else:
			psv_code_gen.write(line+"\n")
		it = it + 1

	psv_code_gen.close()
	
	sys.stdout = sys_stdout

work_space_dir = sys.argv[1]
psrc_fl_dir = sys.argv[2] 
frv_config_path = sys.argv[3]
tpsrc_fl_dir = sys.argv[4] 

if work_space_dir == "":
	print("ERRO NO WORKSPACE DIR")
	exit(1)

if psrc_fl_dir == "":
	print("ERRO NO FILE LIST FILE DIR")
	exit(1)

if frv_config_path == "":
	print("ERRO NO FRV CONFIG DIR")
	exit(1)

frv_config_fd = open(frv_config_path)
frv_config_str = frv_config_fd.read()
frv_config = json.loads(frv_config_str)

src_file_list   = []
gen_file_list	= []

if not os.path.exists(work_space_dir + "/src/src_gen"):
	os.makedirs(work_space_dir + "/src/src_gen")

tpsrc_fl_fd = open(tpsrc_fl_dir,"w")
pv_fl = open(psrc_fl_dir,"r")

line = pv_fl.readline()

while line:
	lc = line.strip().replace("\n","")
	if lc == "":
		line = pv_fl.readline()
		continue
	if lc[0] == "#":
		line = pv_fl.readline()
		continue
	rsrc_path = lc.replace("${workspace}",work_space_dir)
	src_file_list.append(rsrc_path)
	pv_fname  = rsrc_path[rsrc_path.rfind('/')+1:len(rsrc_path)]
	gen_file_list.append(work_space_dir + "/src/src_gen/" + pv_fname[0:pv_fname.rfind('.')] + ".sv")
	tpsrc_fl_fd.write(work_space_dir + "/src/src_gen/" + pv_fname[0:pv_fname.rfind('.')] + ".sv\n")
	line = pv_fl.readline()


for i in range(len(src_file_list)):
	print("INFO\tgenerate %s"%gen_file_list[i])
	vp_psv2sv(parse_configs(src_file_list[i]),gen_file_list[i])

